import React from 'react'
import { connect } from 'react-redux'
import { Mutation } from 'react-apollo'
import {
  Modal, Button, Icon, Header,
} from 'semantic-ui-react'
import { modal as modalDuck } from 'ducks'
import Loading from 'components/loading'

const ConfirmModal = ({ modal, actionClose }) => {
  const {
    graphqlAction, closeAction, icon, title, message, submitValues,
  } = modal.config
  if (modal.isOpen === true && graphqlAction !== undefined) {
    return (
      <Mutation mutation={graphqlAction} onCompleted={() => actionClose(closeAction)}>
        {(addTodo, { data, loading, error }) => (
          <Modal basic size="small" open={modal.isOpen}>
            <Header icon={icon} content={title} />
            <Modal.Content>
              {
                loading && <Loading />
              }
              {error && <p>{error}</p>}
              {!error && <p>{message}</p>}
            </Modal.Content>
            <Modal.Actions>
              <Button basic color="red" inverted onClick={actionClose} disabled={loading}>
                <Icon name="cancel" />
                {' '}
  取消
              </Button>
              <Button
                color="green"
                inverted
                loading={loading}
                disabled={loading}
                onClick={() => addTodo({ variables: submitValues })}
              >
                <Icon name="checkmark" />
                {' '}
  确定
              </Button>
            </Modal.Actions>
          </Modal>
        )}
      </Mutation>
    )
  }
  return null
}

const mapStateToProps = state => ({
  modal: modalDuck.selectors.modal(state),
})

const mapDispatchToProps = {
  actionClose: modalDuck.creators.actionClose,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ConfirmModal)
